#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   new_price_extra.py    
@Contact :   fengfeng.qiu@amh-group.com

@Modify Time      @Author    
------------      -------    
2022/8/1.csv 19:52   qiufengfeng
'''

import json
import requests
import re



def make_predict_text(text):
    new_text_list = []
    for line in text.split("\n"):
        role = line[:2]
        tokens = re.split(r'([，。？])',line[2:])
        for i in range(int(len(tokens)/2)):
            new_text_list.append(role + tokens[i] + tokens[i+1])
    return "".join(new_text_list),new_text_list

def orochi_api(text):
    #url = "https://qa-predict-phantom.amh-group.com/underchat-v0628/v1/models/underchat-v0628:predict"
    url = "http://10.190.198.253:8080/v1/models/underchat:predict"
    header = {
        'Content-Type': "application/json"
    }
    post_data = {
  "remove_fields": [
    "vector",
    "tokens"
  ],
  "config": {
    "stages": {
      "intent-ir": [
        "maxlen-turn-filter-128-v1",
        "intent-hit-turn-filter-v1",
        "simcse-cls-vectorizer-v1",
        "ir-based-intent-model-v2"
      ],
      "intent-merger": [
        "naive-intent-merger-v1"
      ],
      "filter": [
        "maxlen-session-filter-v1"
      ],
      "split-sentence": [
        "sent-segment-v1"
      ],
      "intent-rule": [
        "hotfix-based-intent-model-v1",
        "rule-based-intent-model-v3"
      ]
    },
    "pipeline": [
      "filter",
      "intent-rule",
      "intent-ir",
      "intent-merger"
    ]
  },
  "data": {
    "text": text}
}

    result = 0
    try:
        req = requests.post(url, data=json.dumps(post_data), headers=header)
        return req.json()
    except Exception as e:
        print(e)
    return result



def get_text_list_intents(text):
    result_json = orochi_api(text)
    intents_object = [i for i in result_json['data']['turns']]
    intents = []
    texts = []
    for oj in intents_object:
        item_intents = oj['intents']
        if len(item_intents)> 1:
            intents.append(",".join([i['intent'] for i in item_intents]))
        elif len(item_intents) == 0:
            intents.append("")
        else:
            intents.append(item_intents[0]['intent'])
        texts.append(oj['role'] + "："+ oj['text'])
    if len(texts) != len(intents):
        print("error")
    return "\n".join([i+" "+ j for i,j in zip(intents,texts)])



directed_intent = ["陈述意向价","询问意向价",'询问价格','请求提高价格']
context_intent = {"context":[
    "询问意向价",
    "询问价格",
    "询问价格类型",
    "询问信息费",
    "询问定金",
    "询问油卡",
    "陈述感兴趣货物"
],
"info":[
    "陈述金额",
    "陈述数字",
    "陈述价格",
    "陈述价格类型",
    "陈述信息费",
    "陈述定金",
    '陈述油卡',
    '陈述意向价'
]}

import re
def parse_price(text):
    match = re.search("(\d{2,5})[^0-9吨方米]*",text)
    if match:
        return match.groups()[0]
    else:
        return ""

def get_price(text):
    intents_and_text = text.split("\n")

    intents = [i.split(" ")[0].split(",") for i in intents_and_text]
    texts = ["".join(i.split(" ")[1:]) for i in intents_and_text]

    prices = [parse_price(i) for i in texts]

    driver_price = []
    shipper_price = []

    before_intents = ""
    before_role = ""
    role_total_intents = []
    for its,p,t in zip(intents,prices,texts):
        its1 = [i for i in its if not i.endswith("嗯/啊/哎") or not i.endswith("问候语")]

        if not its1:
            continue
        current_role = t[0]
        if before_role != current_role:
            before_intents = role_total_intents
            role_total_intents = []
            before_role = current_role

        role_total_intents.extend(its1)

        for it in its:
            current_intents = it.split("-")[-1]
            if current_intents in directed_intent:
                if p != "":
                    if current_role == "S":
                        shipper_price.append(p)
                    else:
                        driver_price.append(p)
            else:
                for before_intent in before_intents:
                    before_intent = before_intent.split("-")[-1]
                    if before_intent in context_intent['context'] and current_intents in context_intent['info']:
                        if p != "":
                            if current_role == "S":
                                shipper_price.append(p)
                            else:
                                driver_price.append(p)


    return list(set(driver_price)),list((shipper_price))



def extra_price(text):
    predict_text,predict_list = make_predict_text(text)
    intents_and_texts =  get_text_list_intents(predict_text)

    driver_price,shipper_price = get_price(intents_and_texts)
    return driver_price,shipper_price


if __name__ == '__main__':
    test_string = "D：a。D：喂。S：喂喂。D：啊，2:00到玉林玉州大厦给多少钱？S：嗯，到车3200。D：3200。S：嗯。D：能加一点吗？S：你加不了。D：啊，行，考虑一下啊。S：啊。S：嗯。"
    print(extra_price(test_string))



